/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState } from 'react';
import { Modal, Form, Row, Col, message, Select } from 'antd';
import KbSelect from '@/components/KbSelect';
import { useDispatch } from 'dva';
import { getGridCode, addNewConfig, getUsedSortList } from '@/services/automatic';
import { createPriorities, findMinimum } from '../_utils';
import KeyWordsInput from './KeyWordsInput';

const FormItem = Form.Item;

const AddressSortModal = props => {
  const dispatch = useDispatch();
  const { visible, record, form, onOK, onCancel } = props;
  const {
    id,
    sort = '',
    codes,
    sorting_line_code,
    addr_scheme = '',
    sorting_line_id: sorting_line_id_props,
  } = record || {};
  const { getFieldDecorator, validateFields, resetFields, setFieldsValue, isFieldsTouched } = form;

  const [sorting_line_id, setSortingLineId] = useState('');
  const [gridOptions, setGridOptions] = useState([]);

  const handleOk = () => {
    const isFormChanged = isFieldsTouched();
    validateFields((err, value) => {
      if (err) return;
      if (!isFormChanged) {
        onCancel();
        return;
      }
      addNewConfig({
        ...value,
        addr_scheme: value.addr_scheme.join('、'),
        codes: value.codes.join(','),
        id,
      }).then(res => {
        if (res.code == 0) {
          message.success(res.msg);
          onOK();
        } else {
          message.error(res.msg);
        }
      });
    });
  };
  const handelCancel = () => {
    onCancel();
    resetFields();
  };

  const getSortLine = () =>
    new Promise(resolve => {
      dispatch({
        type: 'automatic/getSortLineList',
        payload: {
          sorting_line_type: 1,
        },
      })
        .then(res => {
          resolve(res.list);
        })
        .catch(() => {
          resolve([]);
        });
    });

  const onSortLineChange = (_, options) => {
    const {
      props: { option = {} },
    } = options || {};
    setSortingLineId(option.id);
    setFieldsValue({
      codes: [],
    });
  };

  const onDropdownVisibleChange = open => {
    const reqId = sorting_line_id || sorting_line_id_props;
    if (reqId && open) {
      getGridCode({
        sorting_line_id: reqId,
        grid_type: 1,
        page: 1,
        size: 2000,
        down_scanner_type: 0,
      }).then(res => {
        setGridOptions(res);
      });
    }
  };

  useEffect(
    () => {
      if (visible) {
        getUsedSortList().then(usedSortList => {
          const minimum = findMinimum(usedSortList);
          setFieldsValue({
            sort: sort || minimum,
            addr_scheme: addr_scheme ? addr_scheme.split('、') : [],
          });
        });
        if (sorting_line_id_props) {
          onDropdownVisibleChange(true);
        } else {
          setGridOptions([]);
          setSortingLineId('');
        }
      }
    },
    [visible, sort, addr_scheme, sorting_line_id_props],
  );

  return (
    <Modal
      destroyOnClose
      title="新增方案"
      width={700}
      visible={visible}
      onOk={handleOk}
      onCancel={handelCancel}
    >
      <Form>
        <FormItem label="匹配优先级" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <Row type="flex" gutter={[20]}>
            <Col>
              {getFieldDecorator('sort', {
                rules: [
                  {
                    required: true,
                    message: '请选择优先级',
                  },
                ],
              })(
                <KbSelect
                  request={async () => createPriorities()}
                  placeholder="请选择优先级"
                  style={{ width: 250 }}
                  allowClear={false}
                />,
              )}
            </Col>
            <Col>
              <span style={{ color: 'red' }}>数字越小，优先级越高</span>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="地址关键字" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('addr_scheme', {
            initialValue: addr_scheme ? addr_scheme.split('、') : [],
            rules: [
              {
                required: true,
                message: '请输入地址关键字',
              },
            ],
          })(<KeyWordsInput />)}
        </FormItem>
        <FormItem label="分拣线" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('sorting_line_code', {
            initialValue: sorting_line_code,
            rules: [
              {
                required: true,
                message: '请选择分拣线',
              },
            ],
          })(
            <KbSelect
              onChange={onSortLineChange}
              placeholder="请选择分拣线"
              style={{ width: 250 }}
              request={getSortLine}
              format="sorting_line_code*sorting_line_name"
            />,
          )}
        </FormItem>
        <FormItem label="格口号" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <Row type="flex" gutter={[20]}>
            <Col>
              {getFieldDecorator('codes', {
                initialValue: codes ? codes.split(',') : [],
                rules: [
                  {
                    required: true,
                    message: '请选择格口号',
                  },
                ],
              })(
                <Select
                  placeholder="请选择格口号"
                  mode="multiple"
                  style={{ width: 250 }}
                  onDropdownVisibleChange={onDropdownVisibleChange}
                >
                  {gridOptions.map(val => (
                    <Select.Option key={val.grid_code} value={val.grid_code}>
                      {val.grid_code}-{val.grid_name}
                    </Select.Option>
                  ))}
                </Select>,
              )}
            </Col>
            <Col>
              <span style={{ color: 'red' }}>可多选</span>
            </Col>
          </Row>
        </FormItem>
      </Form>
    </Modal>
  );
};

export default Form.create()(AddressSortModal);
